package algorithm.recursionAndbacktrack.twoDimensions.floodfill.p200;

/**
 * 200. 岛屿数量
 */
class Solution {
    private int m, n;
    private boolean[][] visited;
    private int[][] d = {{0, -1}, {1, 0}, {0, 1}, {-1, 0}};
    public int numIslands(char[][] grid) {
        if (grid != null) {
            m = grid.length;
        }
        if (m > 0) {
            n = grid[0].length;
        }
        int num = 0;
        if (m > 0 && n > 0) {
            visited = new boolean[m][n];
            for (int i = 0; i < m; i++) {
                for (int j = 0; j < n; j++) {
                    if (!visited[i][j] && grid[i][j] == '1') {
                        num++;
                        dfs(grid, i, j);
                    }
                }
            }
        }

        return num;
    }

    private void dfs(char[][] grid, int x, int y) {
        visited[x][y] = true;
        for (int i = 0; i < d.length; i++) {
            int newX = x + d[i][0];
            int newY = y + d[i][1];
            if (inArea(newX, newY) && !visited[newX][newY] && grid[newX][newY] == '1') {
                dfs(grid, newX, newY);
            }
        }
    }

    private boolean inArea(int x, int y) {
        return x >= 0 && x < m && y >= 0 && y < n;
    }

    public static void main(String[] args) {
        /*char[][] grid = {{'1','1','1','1','0'},
                         {'1','1','0','1','0'},
                         {'1','1','0','0','0'},
                         {'0','0','0','0','0'}};*/
        char[][] grid = {{'1','1','0','0','0'},
                         {'1','1','0','0','0'},
                         {'0','0','1','0','0'},
                         {'0','0','0','1','1'}};
        System.out.println(new Solution().numIslands(grid));
    }
}